package com.example.idachuappone.promptly.item;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.idachuappone.BaseActivity;
import com.example.idachuappone.R;
import com.example.idachuappone.person.item.CookAddressListPersonActivity;
import com.example.idachuappone.person.method.AddressMethod;
import com.example.idachuappone.person.method.AddressMethod.SetAddress;
import com.example.idachuappone.promptly.entity.Addresses;
import com.example.idachuappone.promptly.entity.UserInfo;
import com.example.idachuappone.utils.AppShareData;
import com.example.idachuappone.utils.CusProSmallBgDialog;
import com.example.idachuappone.utils.MainToast;
import com.example.idachuappone.utils.NetUtil;
import com.example.idachuappone.utils.PrefUtil;
import com.lidroid.xutils.bitmap.BitmapGlobalConfig.BitmapCacheManagementTask;

public class CookAddressListActivity extends BaseActivity implements OnClickListener, OnItemClickListener {
	private ListView Lv_address_list;
	private CookAddressAdapter adapter;
	private Button btn_back;
	private Button btn_index;
	private CusProSmallBgDialog cusProDialog;
	private boolean isNoData;
	private boolean isupdateposition;
	private LinearLayout ll_no_data;
	private LinearLayout ll_no_network;
	private String userAddressId;
	private UserInfo userInfo;

	private class CookAddressAdapter extends BaseAdapter {
		private Context context;
		private List<Addresses> list;
		private int userAddressId;

		public void setUserAddressId(int userAddressId) {
			for (int i = 0; i < this.list.size(); i++) {
				if (userAddressId == Integer.parseInt(this.list.get(i).getId())) {
					this.userAddressId = userAddressId;
					return;
				}
			}
			this.userAddressId = Integer.parseInt(this.list.get(0).getId());
		}

		public void setList(List<Addresses> list) {
			this.list = list;
		}

		public CookAddressAdapter(Context context) {
			this.context = context;
		}

		@Override
		public int getCount() {
			return this.list == null ? 0 : this.list.size();
		}

		@Override
		public Object getItem(int position) {
			return this.list == null ? null : (Addresses) this.list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder;
			if (convertView == null) {
				convertView = LinearLayout.inflate(this.context, R.layout.simple_cook_address_list_person, null);
				viewHolder = new ViewHolder();
				viewHolder.tv_address = (TextView) convertView.findViewById(R.id.tv_address);
				viewHolder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
				viewHolder.tv_phone = (TextView) convertView.findViewById(R.id.tv_phone);
				viewHolder.img_check = (ImageView) convertView.findViewById(R.id.img_check);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			Addresses addresses = this.list.get(position);
			String address = addresses.getArea() + addresses.getCommunity() + addresses.getDoor_number();
			if (position == 0) {
				CharSequence text = "\u2605 " + address;
				SpannableStringBuilder builder = new SpannableStringBuilder(text);
				Matcher matcher = Pattern.compile("\u2605").matcher(text);
				while (matcher.find()) {
					builder.setSpan(new ImageSpan(this.context, 2130837635), matcher.start(), matcher.end(),
							17);
				}
				viewHolder.tv_address.setText(builder);
			} else {
				viewHolder.tv_address.setText(address);
			}
			if (this.userAddressId == Integer.parseInt(addresses.getId())) {
				viewHolder.img_check.setVisibility(0);
			} else {
				viewHolder.img_check.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
			}
			viewHolder.tv_name.setText(addresses.getName());
			viewHolder.tv_phone.setText(addresses.getPhone());
			return convertView;
		}
	}

	private class ViewHolder {
		private ImageView img_check;
		private TextView tv_address;
		private TextView tv_name;
		private TextView tv_phone;

		private ViewHolder() {
		}
	}

	public CookAddressListActivity() {
		this.isupdateposition = false;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cook_address_list);
		this.cusProDialog = new CusProSmallBgDialog(this);
		this.cusProDialog.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				CookAddressListActivity.this.cusProDialog.dismiss();
			}
		});
		this.userAddressId = getIntent().getStringExtra("userAddressId");
		initView();
		initDate();
	}

	private void initDate() {
		AddressMethod.getAddressList(this, this.cusProDialog, new SetAddress() {
			@Override
			public void onSuccess(String result) {
				CookAddressListActivity.this.ll_no_network
						.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
				try {
					JSONObject jsonObject = new JSONObject(NetUtil.unescapeUnicode(result));
					if (jsonObject.getInt("code") == 10000) {
						CookAddressListActivity.this.userInfo = new UserInfo();
						CookAddressListActivity.this.userInfo.parseJson(jsonObject.getJSONObject("data"));
						if (CookAddressListActivity.this.userInfo.getAddresses() == null
								|| CookAddressListActivity.this.userInfo.getAddresses().size() <= 0) {
							CookAddressListActivity.this.isNoData = true;
							CookAddressListActivity.this.ll_no_data.setVisibility(0);
							CookAddressListActivity.this.showNoAddressDialog();
							return;
						}
						CookAddressListActivity.this.ll_no_data
								.setVisibility(BitmapCacheManagementTask.MESSAGE_CLEAR_MEMORY_BY_KEY);
						CookAddressListActivity.this.initAdapter();
						if (CookAddressListActivity.this.isupdateposition || CookAddressListActivity.this.isNoData) {
							PrefUtil prefUtil = PrefUtil.getInstance(CookAddressListActivity.this);
							prefUtil.setFimallyLocateCoor(new StringBuilder(String
									.valueOf(CookAddressListActivity.this.userInfo.getAddresses().get(0).getLng()))
									.append(",")
									.append(CookAddressListActivity.this.userInfo.getAddresses().get(0).getLat())
									.toString());
							prefUtil.setArea(CookAddressListActivity.this.userInfo.getAddresses().get(0).getArea());
							prefUtil.setXiaoQu(CookAddressListActivity.this.userInfo.getAddresses().get(0)
									.getCommunity());
							prefUtil.setDoor(CookAddressListActivity.this.userInfo.getAddresses().get(0)
									.getDoor_number());
							prefUtil.setName(CookAddressListActivity.this.userInfo.getAddresses().get(0).getName());
							prefUtil.setUserAddressId(CookAddressListActivity.this.userInfo.getAddresses().get(0)
									.getId());
							prefUtil.setPhone(CookAddressListActivity.this.userInfo.getAddresses().get(0).getPhone());
							CookAddressListActivity.this.isupdateposition = false;
							CookAddressListActivity.this.isNoData = false;
							return;
						}
						return;
					}
					MainToast.show(CookAddressListActivity.this, jsonObject.getString("error"), 0);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onFail() {
				CookAddressListActivity.this.ll_no_network.setVisibility(0);
			}
		});
	}

	private void showNoAddressDialog() {
		Builder builder = new Builder(this);
		builder.setMessage("\u60a8\u8fd8\u6ca1\u6709\u8bbe\u7f6e\u670d\u52a1\u5730\u5740\uff0c\u8bf7\u70b9\u51fb\u786e\u5b9a\u53bb\u8bbe\u7f6e");
		builder.setPositiveButton("\u786e\u5b9a", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				CookAddressListActivity.this.startActivityForResult(new Intent(CookAddressListActivity.this,
						AddAddressActivity.class), 1);
			}
		});
		builder.setNegativeButton("\u53d6\u6d88", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				CookAddressListActivity.this.finish();
			}
		});
		Dialog dialog = builder.create();
		dialog.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss(DialogInterface dialog) {
				CookAddressListActivity.this.finish();
			}
		});
		dialog.show();
	}

	private void initAdapter() {
		this.adapter.setList(this.userInfo.getAddresses());
		try {
			this.adapter.setUserAddressId(Integer.parseInt(this.userAddressId));
		} catch (Exception e) {
			this.adapter.setUserAddressId(0);
		}
		this.adapter.notifyDataSetChanged();
	}

	private void initView() {
		this.ll_no_network = (LinearLayout) findViewById(R.id.ll_no_network);
		this.ll_no_network.setOnClickListener(this);
		this.btn_index = (Button) findViewById(R.id.btn_index);
		this.btn_index.setOnClickListener(this);
		this.btn_back = (Button) findViewById(R.id.btn_back);
		this.btn_back.setOnClickListener(this);
		this.Lv_address_list = (ListView) findViewById(R.id.Lv_address_list);
		this.Lv_address_list.setOnItemClickListener(this);
		this.adapter = new CookAddressAdapter(this);
		this.Lv_address_list.setAdapter(this.adapter);
		this.ll_no_data = (LinearLayout) findViewById(R.id.ll_no_data);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back /* 2131165198 */:
			backSetAddress();
		case R.id.btn_index /* 2131165213 */:
			startActivityForResult(new Intent(this, CookAddressListPersonActivity.class),
					BitmapCacheManagementTask.MESSAGE_FLUSH);
		case R.id.ll_no_network /* 2131165232 */:
			initDate();
		default:
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (AppShareData.isRefreshAddressChoose) {
			initDate();
			AppShareData.isRefreshAddressChoose = false;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1) {
			if (resultCode == -1) {
				boolean temp = data.getBooleanExtra("isupdateposition", false);
				if (temp) {
					this.isupdateposition = temp;
				}
				initDate();
			}
			if (resultCode == 0) {
				finish();
			}
		}
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View arg1, int position, long arg3) {
		this.userAddressId = this.userInfo.getAddresses().get(position).getId();
		initAdapter();
		Intent data = new Intent();
		Bundle bundle = new Bundle();
		bundle.putSerializable("address", this.userInfo.getAddresses().get(position));
		data.putExtras(bundle);
		setResult(-1, data);
		finish();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == 4) {
			backSetAddress();
		}
		return true;
	}

	public void backSetAddress() {
		if (this.userInfo != null && this.userInfo.getAddresses() != null && this.userInfo.getAddresses().size() > 0) {
			int index = 0;
			if (this.userAddressId != null && this.userAddressId.length() > 0) {
				for (int i = 0; i < this.userInfo.getAddresses().size(); i++) {
					if (this.userAddressId.equals(this.userInfo.getAddresses().get(i).getId())) {
						index = i;
						break;
					}
				}
			}
			Intent data = new Intent();
			Bundle bundle = new Bundle();
			bundle.putSerializable("address", this.userInfo.getAddresses().get(index));
			data.putExtras(bundle);
			setResult(-1, data);
			finish();
		}
	}
}
